import { useState, useEffect } from 'react'
import { TagsOutlined } from '@ant-design/icons'
import { Card, Col, Row } from 'antd'
import More from '../more/more'
import './content.scss'
import { isLogin } from '@/utils/auth'
import { useWindowSize } from '@reactuses/core'

function Content(props: { books: any[] }) {
  const { books } = props
  const [num, setNum] = useState<number>(6)
  const { width } = useWindowSize()

  const [booksList, setBooksList] = useState<any[]>([])

  useEffect(() => setBooksList(books), [books])

  // 根据不同尺寸显示不同列
  useEffect(() => {
    if (width < 1200 && width > 800) {
      setNum(8)
    } else if (width < 900 && width > 750) {
      setNum(12)
    } else if (width < 750) {
      setNum(24)
    } else {
      setNum(6)
    }
  }, [width])

  const deleteCallback = (data: { [key: string]: string }, status: string, index: number) => {
    // 创建副本
    const updatedBooksList = [...booksList]

    // 书签索引
    const num = booksList[index]?.children.findIndex((v: any) => v.id === data.id)

    if (status === 'delete') {
      // 删除书签
      updatedBooksList[index].children?.splice(num, 1)
      // 如果删除完书签，把书签列表也删除掉
      if (updatedBooksList[index].children?.length === 0) updatedBooksList.splice(index, 1)
    } else {
      updatedBooksList[index].children[num] = data
    }
    // 更新书签列表
    setBooksList(updatedBooksList)
  }

  return (
    <div>
      {booksList.map((item, index) => (
        <div className="card-list" key={item.id} id={item.id}>
          <h4 className="flex-align-center flex-gap-10 text-color-gary card-list-header">
            <TagsOutlined className="card-label" />
            <span className="card-title">{item.name}</span>
          </h4>

          <p className="text-color-gary card-subtitle">{item.description}</p>

          <Row gutter={16} className="card-item-list">
            {item.children &&
              item.children.map((v: any) => (
                <Col span={num} className="card-col" key={v.id}>
                  <a href={v.url} target="_blank" rel="noreferrer" className="card-link">
                    <Card
                      title={v.name}
                      bordered={false}
                      className="card"
                      extra={
                        isLogin() ? <More data={v} index={index} cb={deleteCallback} /> : <></>
                      }
                    >
                      <p className="p-content">{v.description}</p>
                    </Card>
                  </a>
                </Col>
              ))}
          </Row>
        </div>
      ))}
    </div>
  )
}

export default Content
